import { Card, message, List } from 'antd'
import {
  FormItem, Input, ArrayTable, Editable, FormButtonGroup, Submit, Select, Checkbox, Switch,
  FormLayout, FormGrid,
} from '@formily/antd'
import { createForm, onFormValidateFailed } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { onFieldValueChange, FormPath } from '@formily/core';
import { PageContainer } from '@ant-design/pro-components';
import { request, useRequest, history, useLocation } from 'umi';
import Qs from 'query-string';
//import { layoutActionRef } from '../../app';
import { FIELD, BUTTON_ACTION, BUTTON, METHOD, BUTTON_ACTION_TYPES } from '@/constants/enums';
import { initialEntityValues } from './initialValues';
import { useMount } from 'ahooks';
const { parse } = FormPath;
const SchemaField = createSchemaField({
  components: {
    FormItem,
    Editable,
    Input,
    ArrayTable,
    Select,
    Checkbox,
    Switch,
    FormLayout,
    Card,
    FormGrid
  },
})

const form = createForm({
  effects(form) {
    onFieldValueChange('name', ({ value }) => {
      form.setFieldState('*(page.*.data,record.*.data)', (state: any) => {
        let dataValue = form.getValuesIn(state.address.entire);
        for (let item of dataValue) {
          if (item.name === 'url') {
            let action = form.getValuesIn(parse('.action', state.address.entire).entire);
            item.value = getUrl(action, value)
          }
        }
        function getUrl(action, value) {
          switch (action) {
            case BUTTON_ACTION_TYPES.add:
              return `/api/${value}`;
            case BUTTON_ACTION_TYPES.update:
              return `/api/${value}/:id`;
            case BUTTON_ACTION_TYPES.delete:
              return `/api/${value}/:id`;
            default:
              break;
          }
        }
      });
    })
    onFormValidateFailed((form) => {
      message.error(<List
        bordered
        dataSource={form.errors.map(error => `${error.address} ${error.messages.join(',')}`)}
        renderItem={(item: any) => (
          <List.Item>{item}</List.Item>
        )}
      />);
    })
  }
})

export default function () {
  const location = useLocation();
  const query = Qs.parse(location.search);
  const loadQuery = useRequest((id) =>
    request(`/api/entity/${id}`, {
      method: 'GET'
    }), {
    manual: true,
    onSuccess(data: any) {
      form.setValues(data);
    }
  });
  useMount(() => {
    if (query.id) {
      loadQuery.run(query.id);
    } else {
      form.setValues(initialEntityValues);
    }
  });
  const addQuery = useRequest((values) =>
    request(`/api/entity`, {
      method: 'POST',
      data: values
    }), {
    manual: true,
    onSuccess() {
      //layoutActionRef.current.reload();
      (window as any).layoutActionRef.current.reload();
      history.back();
    },
    formatResult(res) {
      return res;
    }
  });
  const updateQuery = useRequest((id, values) =>
    request(`/api/entity/${id}`, {
      method: 'PUT',
      data: values
    }), {
    manual: true,
    onSuccess() {
      history.back();
    },
    formatResult(res) {
      return res;
    }
  });
  const handleSubmit = (values) => {
    console.log('values', values);
    if (query.id) {
      updateQuery.run(query.id, values);
    } else {
      addQuery.run(values);
    }

  }
  return (
    <PageContainer>
      <FormProvider form={form}>
        <SchemaField>
          <SchemaField.Void
            x-component="FormGrid"
            x-component-props={{ maxColumns: 4, minColumns: 2 }}
          >
            <SchemaField.String
              name="name"
              title="名称"
              x-decorator="FormItem"
              required
              x-component="Input"
            />
            <SchemaField.String
              name="title"
              title="标题"
              x-decorator="FormItem"
              required
              x-component="Input"
            />
          </SchemaField.Void>
          <SchemaField.Array
            name="fields"
            x-decorator="FormItem"
            x-component="ArrayTable"
          >
            <SchemaField.Object>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 50, title: '排序', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.SortHandle"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 80, title: '索引', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.Index"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '名称', dataIndex: 'name', width: 200 }}
              >
                <SchemaField.String
                  name="name"
                  x-decorator="FormItem"
                  required
                  x-component="Input"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '标题', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="title"
                  required
                  x-component="Input"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '类型', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="type"
                  required
                  x-component="Select"
                  enum={FIELD}
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '数据', width: 200 }}
              >
                <SchemaField.Array
                  name="data"
                  title="配置字段数据"
                  x-decorator="Editable.Popover"
                  x-component="ArrayTable"
                  x-reactions={(field: any) => {
                    let value = field.getState().value;
                    if (value.length > 0) {
                      field.title = value.map(item => item.title).join(',');
                    }
                  }}
                >
                  <SchemaField.Object>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '标题', dataIndex: 'name', width: 200 }}
                    >
                      <SchemaField.String
                        name="title"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '值', dataIndex: 'value', width: 200 }}
                    >
                      <SchemaField.String
                        name="value"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{
                        title: '操作',
                        dataIndex: 'operations',
                        width: 200,
                        fixed: 'right'
                      }}
                    >
                      <SchemaField.Void x-component="FormItem">
                        <SchemaField.Void x-component="ArrayTable.Remove" />
                        <SchemaField.Void x-component="ArrayTable.MoveDown" />
                        <SchemaField.Void x-component="ArrayTable.MoveUp" />
                      </SchemaField.Void>
                    </SchemaField.Void>
                  </SchemaField.Object>
                  <SchemaField.Void
                    x-component="ArrayTable.Addition"
                    title="添加字段配置"
                  />
                </SchemaField.Array>
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '支持排序', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="sorter"
                  x-component="Switch"
                  x-reactions={{
                    "dependencies": [".type"],
                    when: "{{$deps[0] === 'number'}}",
                    fulfill: {
                      state: {
                        value: true
                      }
                    },
                    otherwise: {
                      state: {
                        value: false
                      }
                    },
                  }}
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '列表隐藏', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="hideInColumn"
                  x-component="Switch"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '不允许编辑', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="disabled"
                  x-component="Switch"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{
                  title: '操作',
                  dataIndex: 'operations',
                  width: 200,
                  fixed: 'right'
                }}
              >
                <SchemaField.Void x-component="FormItem">
                  <SchemaField.Void x-component="ArrayTable.Remove" />
                  <SchemaField.Void x-component="ArrayTable.MoveDown" />
                  <SchemaField.Void x-component="ArrayTable.MoveUp" />
                </SchemaField.Void>
              </SchemaField.Void>
            </SchemaField.Object>
            <SchemaField.Void
              x-component="ArrayTable.Addition"
              title="添加字段"
            />
          </SchemaField.Array>
          <SchemaField.Array
            name="page"
            x-decorator="FormItem"
            x-component="ArrayTable"
          >
            <SchemaField.Object>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 50, title: '排序', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.SortHandle"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 80, title: '索引', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.Index"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '文本', dataIndex: 'title', width: 200 }}
              >
                <SchemaField.String
                  name="title"
                  x-decorator="Editable"
                  required
                  x-component="Input"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '类型', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="type"
                  required
                  x-component="Select"
                  enum={BUTTON}
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '操作', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="action"
                  required
                  x-component="Select"
                  enum={BUTTON_ACTION}
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '地址', dataIndex: 'url', width: 200 }}
              >
                <SchemaField.Array
                  name="data"
                  title="配置按钮数据"
                  x-decorator="Editable.Popover"
                  x-component="ArrayTable"
                  x-reactions={(field: any) => {
                    let value = field.getState().value;
                    if (value.length > 0) {
                      field.title = '{' + value.map(item => item.name).join(',') + '}';
                    }
                  }}
                >
                  <SchemaField.Object>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '属性1', dataIndex: 'name', width: 200 }}
                    >
                      <SchemaField.String
                        name="name"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '值', dataIndex: 'value', width: 200 }}
                    >
                      <SchemaField.String
                        name="value"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                        x-reactions={{
                          dependencies: ['.name'],
                          when: "{{$deps[0] === 'method'}}",
                          fulfill: {
                            schema: {
                              'x-component': "Select",
                              enum: METHOD
                            }
                          },
                          otherwise: {
                            schema: {
                              'x-component': "Input",
                              enum: null
                            },
                          },
                        }}
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{
                        title: '操作',
                        dataIndex: 'operations',
                        width: 200,
                        fixed: 'right'
                      }}
                    >
                      <SchemaField.Void x-component="FormItem">
                        <SchemaField.Void x-component="ArrayTable.Remove" />
                        <SchemaField.Void x-component="ArrayTable.MoveDown" />
                        <SchemaField.Void x-component="ArrayTable.MoveUp" />
                      </SchemaField.Void>
                    </SchemaField.Void>
                  </SchemaField.Object>
                  <SchemaField.Void
                    x-component="ArrayTable.Addition"
                    title="添加配置"
                  />
                </SchemaField.Array>
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{
                  title: '操作',
                  dataIndex: 'operations',
                  width: 200,
                  fixed: 'right'
                }}
              >
                <SchemaField.Void x-component="FormItem">
                  <SchemaField.Void x-component="ArrayTable.Remove" />
                  <SchemaField.Void x-component="ArrayTable.MoveDown" />
                  <SchemaField.Void x-component="ArrayTable.MoveUp" />
                </SchemaField.Void>
              </SchemaField.Void>
            </SchemaField.Object>
            <SchemaField.Void
              x-component="ArrayTable.Addition"
              title="添加页面操作"
            />
          </SchemaField.Array>
          <SchemaField.Array
            name="record"
            x-decorator="FormItem"
            x-component="ArrayTable"
          >
            <SchemaField.Object>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 50, title: '排序', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.SortHandle"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ width: 80, title: '索引', align: 'center' }}
              >
                <SchemaField.Void
                  x-decorator="FormItem"
                  required
                  x-component="ArrayTable.Index"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '文本', dataIndex: 'title', width: 200 }}
              >
                <SchemaField.String
                  name="title"
                  x-decorator="Editable"
                  required
                  x-component="Input"
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '类型', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="type"
                  required
                  x-component="Select"
                  enum={BUTTON}
                />
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '操作', width: 200 }}
              >
                <SchemaField.String
                  x-decorator="FormItem"
                  name="action"
                  required
                  x-component="Select"
                  enum={BUTTON_ACTION}
                />
              </SchemaField.Void>

              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{ title: '数据', dataIndex: 'data', width: 200 }}
              >
                <SchemaField.Array
                  name="data"
                  title="配置数据"
                  x-decorator="Editable.Popover"
                  x-component="ArrayTable"
                  x-reactions={(field: any) => {
                    let value = field.getState().value;
                    if (value.length > 0) {
                      field.title = '{' + value.map(item => item.name).join(',') + '}';
                    }
                  }}
                >
                  <SchemaField.Object>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '属性', dataIndex: 'name', width: 200 }}
                    >
                      <SchemaField.String
                        name="name"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{ title: '值', dataIndex: 'value', width: 200 }}
                    >
                      <SchemaField.String
                        name="value"
                        x-decorator="FormItem"
                        required
                        x-component="Input"
                        x-reactions={{
                          dependencies: ['.name'],
                          when: "{{$deps[0] === 'method'}}",
                          fulfill: {
                            schema: {
                              'x-component': "Select",
                              enum: METHOD
                            }
                          },
                          otherwise: {
                            schema: {
                              'x-component': "Input"
                            },
                          },
                        }}
                      />
                    </SchemaField.Void>
                    <SchemaField.Void
                      x-component="ArrayTable.Column"
                      x-component-props={{
                        title: '操作',
                        dataIndex: 'operations',
                        width: 200,
                        fixed: 'right'
                      }}
                    >
                      <SchemaField.Void x-component="FormItem">
                        <SchemaField.Void x-component="ArrayTable.Remove" />
                        <SchemaField.Void x-component="ArrayTable.MoveDown" />
                        <SchemaField.Void x-component="ArrayTable.MoveUp" />
                      </SchemaField.Void>
                    </SchemaField.Void>
                  </SchemaField.Object>
                  <SchemaField.Void
                    x-component="ArrayTable.Addition"
                    title="添加配置"
                  />
                </SchemaField.Array>
              </SchemaField.Void>
              <SchemaField.Void
                x-component="ArrayTable.Column"
                x-component-props={{
                  title: '操作',
                  dataIndex: 'operations',
                  width: 200,
                  fixed: 'right'
                }}
              >
                <SchemaField.Void x-component="FormItem">
                  <SchemaField.Void x-component="ArrayTable.Remove" />
                  <SchemaField.Void x-component="ArrayTable.MoveDown" />
                  <SchemaField.Void x-component="ArrayTable.MoveUp" />
                </SchemaField.Void>
              </SchemaField.Void>
            </SchemaField.Object>
            <SchemaField.Void
              x-component="ArrayTable.Addition"
              title="添加记录操作"
            />
          </SchemaField.Array>
        </SchemaField>
        <FormButtonGroup>
          <Submit onSubmit={handleSubmit}>提交</Submit>
        </FormButtonGroup>
      </FormProvider>
    </PageContainer>
  )
}